<script setup lang="ts">
import type { PerBusinessEmployeeApi } from '#/api/per/businessEmployee';

import { computed, onMounted, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import { Button, Card, message, Spin } from 'ant-design-vue';

import { getCurrentEmployeeProfile } from '#/api/per/businessEmployee';
import BusinessMainLog from '#/views/per/businessMainLog/index.vue';

import EmployeeDetail from '../../components/employee/employeeDetail.vue';
import EmployeeEdit from '../../components/employee/employeeEdit.vue';

const mode = ref<'edit' | 'view'>('view');
const desensitize = ref(true);
const personData = ref<null | PerBusinessEmployeeApi.BusinessEmployee>(null);
const saving = ref(false);
const loading = ref(false);
const editRef = ref<any>();
const statusMap = {
  NORMAL: { text: '正式数据', color: 'green' },
  ADD: { text: '新增数据驳回', color: 'blue' },
  DIFF: { text: '修改数据驳回', color: 'orange' },
  READONLY: { text: '审核中', color: 'red' },
};

const [BusinessMainLogDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: BusinessMainLog,
  destroyOnClose: true,
  showConfirmButton: false,
});

const statusText = computed(() => {
  const mode = personData?.value?.highlightMode;
  return statusMap[mode]?.text ?? '未知状态';
});

const statusColor = computed(() => {
  const mode = personData?.value?.highlightMode;
  return statusMap[mode]?.color ?? 'default';
});

function handleEdit() {
  mode.value = 'edit';
}

function handleCancel() {
  mode.value = 'view';
}

const showEditButton = computed(() => {
  const isNormal =
    mode.value === 'view' && personData.value?.highlightMode !== 'READONLY';
  return isNormal;
});

const handleSave = async () => {
  try {
    saving.value = true;
    const result = await editRef.value.handleSave();
    if (result) {
      handleCancel();
      fetchPersonInfo();
      message.success('保存成功');
    } else {
      message.error('保存失败，请检查表单信息');
    }
  } catch (error) {
    console.error(error);
    message.error('保存失败，请检查表单信息');
  } finally {
    saving.value = false;
  }
};

async function toggleDesensitize() {
  desensitize.value = !desensitize.value;
  if (personData.value?.id) {
    personData.value = await getCurrentEmployeeProfile({}, desensitize.value);
  }
}

async function fetchPersonInfo() {
  try {
    loading.value = true;
    const data = await getCurrentEmployeeProfile({}, desensitize.value);
    if (data) personData.value = data;
  } catch (error) {
    console.error(error);
    message.error('刷新失败，请稍后重试');
  } finally {
    loading.value = false;
  }
}

/** 日志信息 */
function handleLog(row: PerBusinessEmployeeApi.BusinessEmployee) {
  formDrawerApi
    .setData({ operateCategoryCode: 'DAJBXX', objectId: row.employeeId })
    .open();
}

onMounted(() => {
  fetchPersonInfo();
});
</script>

<template>
  <div class="profile-page">
    <BusinessMainLogDrawer />
    <Spin :spinning="loading" tip="正在加载中，请稍候...">
      <Card class="profile-card">
        <template #title>
          当前状态：
          <a-tag :color="statusColor">
            {{ statusText }}
          </a-tag>
        </template>

        <template #extra>
          <div
            class="extra-wrapper"
            style="display: flex; gap: 16px; align-items: center"
          >
            <!-- 按钮组 -->
            <div class="action-buttons">
              <Button
                v-if="mode === 'view'"
                type="default"
                :loading="saving"
                @click="handleLog(personData)"
              >
                日志信息
              </Button>
              <Button
                v-if="showEditButton"
                :loading="saving"
                type="primary"
                @click="handleEdit"
              >
                修改信息
              </Button>

              <Button
                v-if="mode === 'view'"
                type="default"
                :loading="saving"
                @click="fetchPersonInfo"
              >
                刷新
              </Button>
              <Button
                v-if="mode === 'view'"
                type="default"
                :loading="saving"
                :danger="desensitize"
                @click="toggleDesensitize"
              >
                <IconifyIcon
                  :icon="
                    desensitize
                      ? 'ant-design:eye-filled'
                      : 'ant-design:eye-invisible-filled'
                  "
                />
                {{ desensitize ? '关闭脱敏' : '启用脱敏' }}
              </Button>

              <Button
                v-if="mode === 'edit'"
                :loading="saving"
                danger
                ghost
                @click="handleCancel"
              >
                取消
              </Button>
              <Button
                v-if="mode === 'edit'"
                :loading="saving"
                type="primary"
                @click="handleSave"
              >
                保存
              </Button>
            </div>
          </div>
        </template>

        <EmployeeDetail v-if="mode === 'view'" :data="personData" />
        <EmployeeEdit
          v-else
          ref="editRef"
          :data="personData"
          @save="handleSave"
          @handle-cancel="handleCancel"
        />
      </Card>
    </Spin>
  </div>
</template>

<style scoped>
.action-buttons {
  display: flex;
  gap: 8px;
}
</style>
